package com.util.boxs.bodys;

import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

/**
 * 矩形刚体
 */
public class RectBody extends HitBody{
    //屏幕尺度对应的属性
    private int pixelHW;//矩形宽度的一半
    private int pixelHH;//矩形高度的一半
    private int pixelWidth;//矩形宽度
    private int pixelHeight;//矩形高度
    //box2d尺度中对应的属性
    private float hw;//在box2d中矩形宽度的一半(box2d规则)
    private float hh;//在box2d中矩形高度的一半

    public RectBody(int pixelX,int pixelY,int width,int height){
        this(pixelX,pixelY,width,height,false);
    }

    public RectBody(int pixelX,int pixelY,int pixelWidth,int pixelHeight,boolean isStatic){
        this.pixelWidth = pixelWidth;
        this.pixelHeight = pixelHeight;
        this.pixelHW = pixelWidth/2;
        this.pixelHH = pixelHeight/2;
        this.pixelX = pixelX;
        this.pixelY = pixelY;
        this.hw = pixel2Mile(pixelHW);
        this.hh = pixel2Mile(pixelHH);
        BodyDef bd = new BodyDef();
        bd.allowSleep = true;//允许休眠
        bd.position = getPixel2MileVec2(pixelX+pixelHW,pixelY-pixelHH);
        bd.type = isStatic? BodyType.STATIC:BodyType.DYNAMIC;

        FixtureDef fd = getDefaultFixtureDef();

        PolygonShape ps = new PolygonShape();
        ps.setAsBox(hw,hh);
        fd.shape = ps;

        body = create(bd,this);
        body.setSleepingAllowed(true);
        body.createFixture(fd);
    }
    @Override
    public void setPosition(int pixelX, int pixelY) {
        body.setTransform(getPixel2MileVec2(pixelX+this.pixelHW,pixelY-this.pixelHH),body.getAngle());
    }

    @Override
    public int getPixelX(){
        return mile2Pixel(body.getPosition().x-hw);
    }
    @Override
    public int getPixelY(){
        return toPixelHeight(body.getPosition().y+hh);
    }
    /**
     * 返回刚体在屏幕尺度的宽
     * @return
     */
    public int getPixelWidth(){
        return pixelWidth;
    }
    /**
     * 返回刚体在屏幕尺度的高
     * @return
     */
    public int getPixelHeight(){
        return pixelHeight;
    }


}
